#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "Log.hpp"

using namespace LogModule;

#define BUFF_SIZE 1024
const int defaultfd = -1;

class UdpServer
{
    using func_t = std::function<std::string(const std::string &)>;
public:
    UdpServer(uint16_t port, func_t func)
        : _sockfd(defaultfd)
        , _port(port)
        , _isrunning(false)
        , _func(func)
    {
        // 1.创建套接字，（网络类型，UDP协议）获取网络文件描述符
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd: " << _sockfd;

        // 2.bind，绑定（通信类型，端口号port，IP）
        // 2.1 创建结构sockaddr_in, (man inet_addr)，填充字段
        struct sockaddr_in peer;
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_port);
        // 2.2 ip地址是一个结构，结构存放一个32位无符号整数
        // ip是一个字符串，192.168.1.1, 1.转成数字 2.转成网络序列 -> inet_addr
        // peer.sin_addr.s_addr = inet_addr(_ip.c_str());
        peer.sin_addr.s_addr = INADDR_ANY; // 任意IP
        // 2.3 绑定
        int n = bind(_sockfd, (struct sockaddr *)&peer, sizeof(peer));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd: " << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 3.服务端收数据
            char buff[BUFF_SIZE];
            struct sockaddr_in peer;
            socklen_t addrlen = sizeof(struct sockaddr_in);
            ssize_t n = recvfrom(_sockfd, buff, BUFF_SIZE, 0, (struct sockaddr *)&peer, &addrlen);

            // 4.消息处理
            buff[n] = 0;
            std::string result = _func(buff);

            // 5.服务端发送数据回客户端
            ssize_t ret = sendto(_sockfd, result.c_str(), result.size(), 0, (const struct sockaddr *)&peer, addrlen);
            (void)ret;
        }
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip;  //不需要，任意IP
    bool _isrunning;
    func_t _func;
};